package com.netty.demo.nio.handler;

import com.netty.demo.protocol.packet.*;
import com.netty.demo.utils.ConsoleUtils;
import com.netty.demo.utils.LoginUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx){
        if (!LoginUtils.hasLogin(ctx.channel())) {
            System.out.println(new Date() + ": 客户端开始登录");

            // 创建登录对象
            LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
            loginRequestPacket.setUserId(LoginUtils.createUserId());
            loginRequestPacket.setUsername("zhangqiang");
            loginRequestPacket.setPassword("pwd");

            // 编码
            ByteBuf buffer = PacketCodec.INSTANCE.encoder(ctx.alloc().buffer(), loginRequestPacket);

            // 写数据
            ctx.channel().writeAndFlush(buffer);
        } else {
            ConsoleUtils.startClientConsoleThread(ctx.channel());
        }
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        ByteBuf byteBuf = (ByteBuf) msg;

        Packet packet = PacketCodec.INSTANCE.decoder(byteBuf);

        if (packet instanceof LoginResponsePacket) {
            LoginResponsePacket loginResponsePacket = (LoginResponsePacket) packet;
            if (loginResponsePacket.isSuccess()) {
                System.out.println(new Date() + ": 客户端登录成功");
                LoginUtils.markLogin(ctx, loginResponsePacket.getUserId());
                ConsoleUtils.startClientConsoleThread(ctx.channel());
            } else {
                System.out.println(new Date() + ": 客户端登录失败，原因：" + loginResponsePacket.getReason());
            }
        } else if (packet instanceof MessagePacket) {
            MessagePacket messagePacket = (MessagePacket) packet;
            System.out.println("服务器想你发来消息：" + messagePacket.getMessage());
            System.out.println("输入消息发送至服务端: ");
        }
    }
}
